package com.jd.jobkeeper.server.service.db.impl;

import com.jd.jobkeeper.server.data.entity.LockInfo;
import com.jd.jobkeeper.server.data.pesistence.LockInfoRepository;
import com.jd.jobkeeper.server.service.lock.LockService;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.concurrent.TimeUnit;

@Service
public class DBLockServiceImpl implements LockService {

    @Resource
    LockInfoRepository lockInfoRepository;

    @Override
    public Lock newLock(String lockName) {
        return new DBLock(lockName,"test");
    }

    class DBLock implements Lock {
        final LockInfo lockInfo;

        public DBLock(String lockName, String nodeId) {
            lockInfo = new LockInfo();
            lockInfo.setUniqueKey(lockName);
            lockInfo.setNodeId(nodeId);
            lockInfo.setExpireTime(TimeUnit.MILLISECONDS.toSeconds(5));
        }

        @Override
        public boolean tryLock() {
            LockInfo result = lockInfoRepository.saveAndFlush(lockInfo);
            lockInfo.setId(result.getId());
            return result != null;
        }

        @Override
        public boolean unLock() {
            lockInfoRepository.deleteById(lockInfo.getId());
            return true;
        }
    }
}
